package com.lagou.niancheng.mvc.dispatcher.core;

import com.lagou.niancheng.mvc.dispatcher.annotations.MyController;
import com.lagou.niancheng.mvc.dispatcher.annotations.MyService;
import com.lagou.niancheng.mvc.dispatcher.entity.ScannedClassMetaData;
import com.lagou.niancheng.mvc.dispatcher.io.ResolverUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.Set;

/**
 * mvc扫描器，负责扫描指定包并解析这些包中 @MyService、@MyController注解
 * 封装成类型信息对象
 *
 * @description: default
 * @author: 阿秋@niancheng
 * @date: 2020/4/8
 */
public class MyMvcScanner {

    private List<ScannedClassMetaData> scannedClassMetaDataList;

    @SuppressWarnings("unchecked")
    public void scan(String packageName) {
        ResolverUtil resolverUtil = new ResolverUtil();
        ResolverUtil allClass = resolverUtil.findImplementations(Object.class, packageName);
        Set<Class> classes = allClass.getClasses();
        if (classes != null) {
            for (Class aClass : classes) {
                // 扫描MyService和MyController组件
                MyService myService = (MyService) aClass.getAnnotation(MyService.class);
                MyController myController = (MyController) aClass.getAnnotation(MyController.class);
                if (myService == null && myController == null) {
                    continue;
                }
                // 创建一个扫描类信息
                ScannedClassMetaData scannedClassMetaData = new ScannedClassMetaData();
                scannedClassMetaData.setBeanType(aClass);
                String name = aClass.getSimpleName();
                if (myController != null) {
                    scannedClassMetaData.setController(true);
                    if (!myController.value().isEmpty()) {
                        name = myController.value();
                    }
                } else {
                    scannedClassMetaData.setController(false);
                    if (!myService.value().isEmpty()) {
                        name = myService.value();
                    }
                }
                scannedClassMetaData.setBeanName(name);
                addScannedClass(scannedClassMetaData);
            }

        }
    }

    private void addScannedClass(ScannedClassMetaData scannedClassMetaData) {
        if (scannedClassMetaDataList == null) {
            scannedClassMetaDataList = new ArrayList<>();
        }
        scannedClassMetaDataList.add(scannedClassMetaData);
    }

    /**
     * 获取所有扫描过的类（mvc感兴趣的）
     *
     * @return
     */
    public List<ScannedClassMetaData> getAllClass() {
        return scannedClassMetaDataList;
    }


}
